package com.ui.service.Impl;

import java.util.List;

import com.ui.dao.JedisDao;
import com.ui.service.ProductService;
import com.wanmei.commons.JsonUtils;
import com.wanmei.mapper.ProductMapper;
import com.wanmei.pojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper mapper;

    @Autowired
    private JedisDao jedisDao;

    @Value("${REDIS_PRODUCT_KEY}")
    private String REDIS_PRODUCT_KEY;

    @Override
    public List<Product> getProductList() {
        // TODO Auto-generated method stub
        return mapper.findAll();
    }

    @Override
    public Product selectByPrimaryKey(Integer pid) {
        // TODO Auto-generated method stub
        // 判断redis中是否存在缓存如果有，从redis中获取
        String key=REDIS_PRODUCT_KEY+"_"+pid;
        String value = jedisDao.get(key);
        if(value != null) {
            return JsonUtils.jsonToPojo(value, Product.class);
        }
        // 如果没有去数据库中查找
        Product product = mapper.selectByPrimaryKey(pid);
        //將查詢出的記錄存入到redis中
        try {
            jedisDao.set(key,JsonUtils.objectToJson(product));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return product;
    }

}
